# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import codecs
import json
from scrapy.exceptions import DropItem


class CnblogsspiderPipeline(object):
    def __init__(self):
        self.file = codecs.open('pagers.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        if item.get('title'):
            line = json.dumps(dict(item), ensure_ascii=False) + "\n"
            self.file.write(line)
            return item
        else:
            raise DropItem("Missing title in %s" % item)

    # 当spider被调用时，这个方法触发
    def spider_closed(self, spider):
        self.file.close()
